import { Request, Response } from 'express';
import { PrismaClient } from '@prisma/client';
import * as bcrypt from 'bcrypt';
import { ResponseHelper } from '../utils/response';
import { generateToken } from '../middleware/auth';
import wechatAuthService from '../utils/WechatAuthService';

const prisma = new PrismaClient();

/**
 * 小程序登录请求体接口
 */
interface MiniprogramLoginBody {
  code: string;
  nickname?: string;
  avatarUrl?: string;
}

/**
 * 管理员登录请求体接口
 */
interface AdminLoginBody {
  username: string;
  password: string;
}

/**
 * 小程序登录
 * POST /api/v1/auth/miniprogram/login
 */
export const miniprogramLogin = async (req: Request, res: Response): Promise<void> => {
  try {
    const { code, nickname, avatarUrl } = req.body as MiniprogramLoginBody;

    // 验证必填参数
    if (!code) {
      ResponseHelper.validationError(res, [
        { field: 'code', message: '微信登录code不能为空' }
      ]);
      return;
    }

    // 调用微信接口获取openid和session_key
    const wechatResult = await wechatAuthService.getOpenidByCode(code);

    if (!wechatResult.success || !wechatResult.data) {
      ResponseHelper.error(res, wechatResult.error || '微信登录失败', 400);
      return;
    }

    const { openid, session_key, unionid } = wechatResult.data;

    // 查找或创建用户
    let user = await prisma.user.findUnique({
      where: { openid }
    });

    if (user) {
      // 用户已存在，更新session_key和其他信息
      user = await prisma.user.update({
        where: { openid },
        data: {
          sessionKey: session_key,
          unionid,
          ...(nickname && { nickname }),
          ...(avatarUrl && { avatarUrl })
        }
      });
    } else {
      // 创建新用户
      user = await prisma.user.create({
        data: {
          openid,
          sessionKey: session_key,
          unionid,
          nickname: nickname || '小程序用户',
          avatarUrl,
          role: 'USER'
        }
      });
    }

    // 生成JWT token
    const token = generateToken(user.id, user.role, user.openid);

    // 返回成功响应
    ResponseHelper.success(res, {
      token,
      user: {
        id: user.id,
        openid: user.openid,
        nickname: user.nickname,
        avatarUrl: user.avatarUrl,
        role: user.role
      }
    }, '登录成功');

  } catch (error: any) {
    console.error('小程序登录失败:', error);
    ResponseHelper.serverError(res, '登录失败，请稍后重试', error);
  }
};

/**
 * 管理员登录
 * POST /api/v1/auth/admin/login
 */
export const adminLogin = async (req: Request, res: Response): Promise<void> => {
  try {
    const { username, password } = req.body as AdminLoginBody;

    // 验证必填参数
    if (!username || !password) {
      ResponseHelper.validationError(res, [
        ...((!username) ? [{ field: 'username', message: '用户名不能为空' }] : []),
        ...((!password) ? [{ field: 'password', message: '密码不能为空' }] : [])
      ]);
      return;
    }

    // 查找管理员用户
    const admin = await prisma.user.findFirst({
      where: {
        username,
        role: 'ADMIN'
      }
    });

    if (!admin) {
      ResponseHelper.unauthorized(res, '用户名或密码错误');
      return;
    }

    // 验证密码
    if (!admin.password) {
      ResponseHelper.serverError(res, '管理员账号配置错误');
      return;
    }

    const passwordMatch = await bcrypt.compare(password, admin.password);

    if (!passwordMatch) {
      ResponseHelper.unauthorized(res, '用户名或密码错误');
      return;
    }

    // 生成JWT token
    const token = generateToken(admin.id, admin.role, admin.openid);

    // 返回成功响应
    ResponseHelper.success(res, {
      token,
      admin: {
        id: admin.id,
        username: admin.username,
        nickname: admin.nickname,
        role: admin.role
      }
    }, '登录成功');

  } catch (error: any) {
    console.error('管理员登录失败:', error);
    ResponseHelper.serverError(res, '登录失败，请稍后重试', error);
  }
};

/**
 * 获取当前用户信息
 * GET /api/v1/auth/me
 * 需要JWT认证
 */
export const getCurrentUser = async (req: Request, res: Response): Promise<void> => {
  try {
    if (!req.user) {
      ResponseHelper.unauthorized(res, '未登录');
      return;
    }

    // 从数据库获取最新的用户信息
    const user = await prisma.user.findUnique({
      where: { id: req.user.id },
      select: {
        id: true,
        openid: true,
        username: true,
        nickname: true,
        avatarUrl: true,
        role: true,
        createdAt: true
      }
    });

    if (!user) {
      ResponseHelper.notFound(res, '用户不存在');
      return;
    }

    ResponseHelper.success(res, user, '获取成功');

  } catch (error: any) {
    console.error('获取用户信息失败:', error);
    ResponseHelper.serverError(res, '获取用户信息失败', error);
  }
};
